<?php

namespace App\Http\Controllers\Admin;

use App\Models\ActivitySale as Offer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LayuiController as Layui;
use App\Exceptions\FormException;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;
use Mockery\Exception;

class OfferController extends Controller
{
    /**
     * 列表页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.offer.index');
    }

    /**
     * 获取数据
     * @return [json]           [数组格式]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        $activityData = Offer::orderBy('id', 'DESC')
            ->where(function ($query) use ($payload) {
                $query->Where('activity_type', Offer::RULE_TYPE_ONE);
                $query->Where('issue_type', 1);
                if (isset($payload['status']) && $payload['status'] != '') {
                    $query->Where('status', $payload['status']);
                }
            })
            ->paginate($request->get('limit', 10));
        return Layui::tableJson($activityData, 0, 1);
    }


    /**
     * 添加页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function create()
    {
        if (View::exists('Admin/offer/add')) {
            return view('Admin/offer/add');
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 添加请求
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function store(Request $request)
    {

        $payload = $request->all(['activity_name', 'full', 'less', 'not_in_goods', 'scope', 'start_at', 'end_at']);

        $rule = [
            'activity_name' => 'required',
            'full' => ['required','numeric', 'gte:less',function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('减多少请输入数字');
                    }
                }
            }],
            'less' => ['required','numeric', 'lte:full',function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('减多少请输入数字');
                    }
                }
            }],
            'scope' => 'required|in:1,2',//
            'end_at' =>  'required|date|after_or_equal:start_at',
            'start_at' => 'required|date',
            'not_in_goods' => ['required_if:scope,2', function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[,0-9]+$/',$value)  ) {
                        return $fail('请输入不参与该满减活动的商品ID，用“，”隔开');
                    }
                }
            }],
        ];
        $message = [
            'activity_name.required' => '请输入活动名称',
            'full.required' => '请输入满多少',
            'full.numeric' => '满多少请输入数字',
            'full.gte' => '满多少请输入大于等于减的数字',
            'less.required' => '请输入减多少',
            'less.numeric' => '减多少请输入数字',
            'less.lte' => '减多少请输入小于等于满的数字',
            'not_in_goods.required_if' => '请输入不参与该满减活动的商品ID，用“，”隔开',
            'scope.in' => '请选择活动状态',//
            'start_at.date' => '输入正确的时间',
            'end_at.date' => '输入正确的时间',
            'end_at.after_or_equal' => '结束时间应大于开始时间',
        ];
        Validator::make($payload, $rule, $message)->validate();
        if ($payload['scope'] == Offer::SCOPE_FUll){
            $payload['not_in_goods'] = '';
        }
        $payload['activity_type'] = Offer::RULE_TYPE_ONE;

        try {
            Offer::create($payload);
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功', route('offer.index'));
    }


    /**
     * 编辑页面
     *
     * @Author   stonefall
     * @DateTime 2019-05-31
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function edit($id)
    {
        if (View::exists('Admin/offer/edit')) {
            $data = Offer::find($id);
            $data['end_at'] = substr($data['end_at'],0,10);
            $data['start_at'] =substr($data['start_at'],0,10);
            return view('Admin/offer/edit', compact('data'));
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 修改请求
     *
     * @Author   stonefall
     * @DateTime 2019-05-31
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function update(Request $request, $id)
    {

        $payload = $request->all(['activity_name', 'full', 'less', 'not_in_goods', 'scope', 'start_at', 'end_at']);

        $rule = [
            'activity_name' => 'required',
            'full' => ['required','numeric', 'gte:less',function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('减多少请输入数字');
                    }
                }
            }],
            'less' => ['required','numeric', 'lte:full',function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('减多少请输入数字');
                    }
                }
            }],
            'scope' => 'required|in:1,2',//
            'end_at' =>  'required|date|after_or_equal:start_at',
            'start_at' => 'required|date',
            'not_in_goods' => ['required_if:scope,2', function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[,0-9]+$/',$value)  ) {
                        return $fail('请输入不参与该满减活动的商品ID，用“，”隔开');
                    }
                }
            }],
        ];
        $message = [
            'activity_name.required' => '请输入活动名称',
            'full.required' => '请输入满多少',
            'less.required' => '请输入减多少',
            'full.numeric' => '满多少请输入数字',
            'full.gte' => '满多少请输入大于等于减的数字',
            'less.numeric' => '减多少请输入数字',
            'less.lte' => '减多少请输入小于等于满的数字',
            'not_in_goods.required_if' => '请输入不参与该满减活动的商品ID，用“，”隔开',
            'scope.in' => '请选择活动状态',//
            'start_at.date' => '输入正确的时间',
            'end_at.date' => '输入正确的时间',
            'end_at.after_or_equal' => '结束时间应大于开始时间',
        ];
        Validator::make($payload, $rule, $message)->validate();
        if ($payload['scope'] == Offer::SCOPE_FUll){
            $payload['not_in_goods'] = '';
        }
        try {
            if ($id) {
                Offer::where(['id' => $id])->update($payload);
            } else {
                throw new Exception('参数错误');
            }
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功', route('offer.index'));
    }

    /**
     * 修改状态请求
     *
     * @Author   stonefall
     * @DateTime 2019-05-31
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function upstatus(Request $request, $id)
    {
        try {
            $activity = Offer::findOrFail($id);
            $activity->status = $activity->status == 1 ? 2 : 1;
            $activity->save();
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponse('操作成功');
    }





    /**
     * 删除
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    [type]     $request [description]
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function destroy(Request $request, $id)
    {
        \DB::beginTransaction();
        try {
            Offer::destroy($id);
        } catch (\Exception $exception) {
            \DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败');
        }
        \DB::commit();
        return $this->getResponse('操作成功');
    }
}
